package com.prdiot.poetry.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.prdiot.poetry.dao.AuthorRepository;
import com.prdiot.poetry.dao.ChengyuRepository;
import com.prdiot.poetry.dao.MingjuRepository;
import com.prdiot.poetry.domains.Author;
import com.prdiot.poetry.domains.Chengyu;
import com.prdiot.poetry.domains.Mingju;
import com.prdiot.poetry.domains.Poems;
import com.prdiot.poetry.service.AuthorService;
import com.prdiot.poetry.service.ChengyuService;
import com.prdiot.poetry.service.MingjuService;
import com.prdiot.poetry.service.PoemsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class BaiduPushUtils {

    @Autowired
    PoemsService poemsService;

    @Autowired
    MingjuRepository mingjuRepository;

    @Autowired
    ChengyuRepository chengyuRepository;

    @Autowired
    AuthorRepository authorRepository;


    @Scheduled(cron = "01 01 01 * * *")
    public void pushUrl(){
        String url = "http://data.zz.baidu.com/urls?site=https://poetry.prdiot.com&token=j43DAB1EegmeFG3Q";
        boolean next = true;
        int patchNum = 200;
        while (next){
            next = false;
            List<Poems> poemsList = poemsService.getRandPoetryToBaidu();
            List<String> urls = new ArrayList<>();
            int i = 0;
            for (Poems poems:poemsList) {
                i++;
                urls.add("https://poetry.prdiot.com/poetry/" + poems.getCode());
                if (i >= patchNum){
                    break;
                }
            }
            String result = postTuiSong(url,urls);
            JSONObject jsonObject = JSON.parseObject(result);
            if (jsonObject!=null){
                int success =  Integer.valueOf(jsonObject.get("success").toString());
                int remain =  Integer.valueOf(jsonObject.get("remain").toString());
                if (remain>0 ){
                    next = true;
                    if (remain<patchNum){
                        patchNum = remain;
                    }
                }
            }
            urls.clear();
        }
        System.out.println("推送结束");

    }

    @Scheduled(cron = "51 58 21 * * *")
    public void genTxt(){
        String domain = "https://poetry.prdiot.com/";
        int lineLimit = 49999;
        //生成poems txt
        List<Author> poemsList = authorRepository.findAll();
        String lineSeparator = System.getProperty("line.separator", "\n");
        int txtIndex = 1;
        String param = "author";
        String filepath = "D:/poetrysitemap/" + param + txtIndex + ".txt";
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter(filepath);
            int index = 0;
            for (Author author:poemsList) {
                index++;
                if (index < lineLimit){
                    fileWriter.write(domain + param + "/" + author.getAuthorId() + lineSeparator);//写入 换行
                }
                if (index >= lineLimit){
                    fileWriter.write(domain + param + "/" + author.getAuthorId());//写入 换行
                    System.out.println(param+txtIndex+".txt");
                    fileWriter.flush();
                    fileWriter.close();
                    txtIndex++;
                    filepath = "D:/poetrysitemap/" + param + txtIndex + ".txt";
                    fileWriter = new FileWriter(filepath);
                    index = 0;
                }
            }

            fileWriter.flush();
            fileWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    /**
     * 百度链接实时推送
     * @param Parameters 提交的链接数组：
     * http://www.example.com/1.html
     * http://www.example.com/2.html
     * @return
     */
    public static String postTuiSong(String url,List<String> Parameters){
        String PostUrl=url;
        if(null==PostUrl || null==Parameters || Parameters.size()==0){
            return null;
        }
        String result = "";
        PrintWriter out = null;
        BufferedReader in = null;
        try {
            //建立URL之间的连接
            URLConnection conn = new URL(PostUrl).openConnection();
            //HttpURLConnection conn = (HttpURLConnection)new URL(PostUrl).openConnection();
            //if(conn.getResponseCode()!=200){
            //设置通用的请求属性
            conn.setRequestProperty("User-Agent", "curl/7.12.1");
            conn.setRequestProperty("Host", "data.zz.baidu.com");
            conn.setRequestProperty("Content-Type", "text/plain");
            conn.setRequestProperty("Content-Length", "83");
            //发送POST请求必须设置如下两行
            conn.setDoInput(true);
            conn.setDoOutput(true);
            //获取conn对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            //发送请求参数
            String param = "";
            for(String s : Parameters){
                param += s+"\n";
            }
            out.print(param.trim());
            //进行输出流的缓冲
            out.flush();
            //通过BufferedReader输入流来读取Url的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while((line=in.readLine()) != null){
                result += line;
            }
            //}
        } catch (Exception e) {
            System.out.println("post推送出现异常！"+e);
//            e.printStackTrace();
        } finally{
            try{
                if(out != null){
                    out.close();
                }
                if(in != null){
                    in.close();
                }
            }catch(IOException ex){
                ex.printStackTrace();
            }
        }
        System.out.println("post推送结果："+result);
        return result;
    }
}
